package cn.cqnu.utils;

import cn.cqnu.global.SystemConstant;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwtUtils
 *
 * jwt载荷部分, - type字段用来区分当前登录用户的类型 - id保存登录用户的studentId或者managerId
 * 签名加密HS256, 秘钥为 638D965456A43AAE25C136F6BF816085 ("cqnu" 通过 md5机密)
 *
 * @author Wei
 * @date 2024/01/20
 */
public class JWTUtils {


    /**
     * 工具类私有化构造 无法实例化
     */
    private JWTUtils() {
    }

    ;

    // 秘钥
    public static final String secretKey = "638D965456A43AAE25C136F6BF816085";

    // 过期时间单位s
    public static final Long expiration = SystemConstant.JSON_TOKEN_EXPIRATION;


    //public static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAl


    /**
     * 颁发JWT
     *
     * @param id   身份证件
     * @param type 类型
     * @return {@link String}
     */
    public static String generateJWT(Long id, Integer type) {

        //    JWT头部保持默认不设置

        //    设置JWT载荷
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", id);
        payload.put("type", type);

        // 设置过期时间
        long currentTimeMillis = System.currentTimeMillis();
        long expireTime = currentTimeMillis + expiration * 1000; // 秒转换为毫秒
        Date expiresAt = new Date(expireTime);


        String jwt = JWT.create().withClaim("id", id).withClaim("type", type)
                .withExpiresAt(expiresAt)
                .sign(Algorithm.HMAC256(secretKey));

        return jwt;
    }


    /**
     * 判断JWT是否有效
     *
     * @param token
     * @return {@link Boolean}
     */
    public static Boolean verify(String token){
        try {
            DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SystemConstant.JSON_TOKEN_SECRET_KEY)).build().verify(token);
            // 成功解析返回true
            return true;
        }catch (Exception e){
            // 抛出异常证明token过期或者无效
            return false;
        }
    }

    /**
     * 获取有效载荷
     *
     * @param token
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public static Map<String, Object> getPayload(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SystemConstant.JSON_TOKEN_SECRET_KEY)).build().verify(token);
        HashMap<String, Object> res = new HashMap<>();

        res.put("id", decodedJWT.getClaim("id").asLong());
        res.put("type", decodedJWT.getClaim("type").asInt());
        return res;
    }

}
